package com.owen.spring.cloud.seata.at.handler;

import com.alibaba.fastjson.JSONObject;
import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.core.model.GlobalStatus;
import io.seata.tm.api.GlobalTransaction;
import io.seata.tm.api.GlobalTransactionContext;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

@Log4j2
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理其他异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value =Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public JSONObject exceptionHandler(HttpServletRequest req, Exception e){
//        String xid = RootContext.getXID();

        // 当获取异常后依然回滚当前事务
//        GlobalTransaction globalTransaction = GlobalTransactionContext.getCurrentOrCreate();
        try {
            GlobalTransaction globalTransaction = GlobalTransactionContext.reload(RootContext.getXID());

            GlobalStatus status = globalTransaction.getStatus();
            System.out.println(status);

            System.out.println("=====rollback=====");
            globalTransaction.rollback();
        } catch (TransactionException ex) {
            ex.printStackTrace();
        }

        log.error("未知异常！原因是:",e);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code","error");
        return jsonObject;
    }

}
